package com.cimctech.socketdemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.cimctech.socketdemo.MyLog;

public class SocketThread extends Thread {
    private static final String TAG = "SocketThread";
    private String ip = "123.103.63.36";
    private int port = 5959;
    private int timeout = 30000;

    public Socket client = null;
    PrintWriter out;
    BufferedReader in;
    public boolean isRun = true;
    Handler inHandler;
    Handler outHandler;
    Context ctx;
    private String TAG1 = "===Send===";
    SharedPreferences sp;

    public SocketThread(Handler handlerin, Handler handlerout, Context context) {
        inHandler = handlerin;
        outHandler = handlerout;
        ctx = context;
        Log.e(TAG, "创建线程socket");
    }

    /**
     * 连接socket服务器
     */
    public void conn() {
        try {
            Log.i(TAG, "连接中……");
            client = new Socket();
            client.connect(new InetSocketAddress(ip, port), 30000);
            Log.e(TAG, "socket...连接成功");
            client.setSoTimeout(timeout);// 设置阻塞时间
            client.setTcpNoDelay(true);

            in = new BufferedReader(new InputStreamReader(client.getInputStream()));

            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
            Log.e(TAG, "输入输出流获取成功");
        } catch (UnknownHostException e) {
            Log.e(TAG, "连接错误UnknownHostException 重新获取");
            e.printStackTrace();
            conn();
        } catch (IOException e) {
            Log.e(TAG, "连接服务器io错误");
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "连接服务器错误Exception" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 实时接受数据
     */
    @Override
    public void run() {
        Log.e(TAG, "线程socket开始运行");
        conn();
        Log.e(TAG, "1.run开始");
        String line = "";
        while (isRun) {
            try {
                if (client != null) {
                    Log.e(TAG, "2.检测数据");

                    Log.e(TAG, "run: 正在接收数据...");
                    Log.e(TAG, "run: 读取流---" + in.readLine());
                    while ((line = in.readLine()) != null) {
                        Log.e(TAG, "4.start set Message");
                        Message msg = inHandler.obtainMessage();
                        msg.obj = line;
                        inHandler.sendMessage(msg);// 结果返回给UI处理
                        Log.e(TAG1, "5.send to handler");
                    }

                } else {
                    Log.e(TAG, "没有可用连接");
                    conn();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "数据接收错误" + e.getMessage());

            }

            /* * * * * * * * * * Socket 客户端读取服务器端响应数据 * * * * * * * * * */
//            try {
//                // serverSocket.isConnected 代表是否连接成功过
//                // 判断 Socket 是否处于连接状态
//                if (client.isConnected() && !client.isClosed()) {
//                    // 客户端接收服务器端的响应，读取服务器端向客户端的输入流
//                    InputStream isRead = client.getInputStream();
//                    // 缓冲区
//                    byte[] buffer = new byte[isRead.available()];
//                    // 读取缓冲区
//                    isRead.read(buffer);
//                    // 转换为字符串
//                    String responseInfo = new String(buffer);
//                    // 日志中输出
//                    Log.e(TAG,"Socket Server"+ responseInfo);
//                }
//                // 关闭网络
//                client.close();
//            } catch (UnknownHostException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
    }

    /**
     * 发送数据
     *
     * @param mess
     */
    public void Send(String mess) {
        try {
            if (client != null) {
                Log.e(TAG1, "发送" + mess + "至"
                        + client.getInetAddress().getHostAddress() + ":"
                        + String.valueOf(client.getPort()));
                out.println(mess);
                out.flush();
                Log.e(TAG1, "发送成功");
                Message msg = outHandler.obtainMessage();
                msg.obj = mess;
                msg.what = 1;
                outHandler.sendMessage(msg);// 结果返回给UI处理
            } else {
                Log.e(TAG, "activity_main 不存在");
                Message msg = outHandler.obtainMessage();
                msg.obj = mess;
                msg.what = 0;
                outHandler.sendMessage(msg);// 结果返回给UI处理
                Log.e(TAG, "连接不存在重新连接");
                conn();
            }

        } catch (Exception e) {
            Log.e(TAG1, "send error");
            e.printStackTrace();
        } finally {
            Log.e(TAG1, "发送完毕");

        }
    }

    /**
     * 关闭连接
     */
    public void close() {
        try {
            if (client != null) {
                Log.e(TAG, "close in");
                in.close();
                Log.e(TAG, "close out");
                out.close();
                Log.e(TAG, "close activity_main");
                client.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "close err");
            e.printStackTrace();
        }

    }
}
